from rest_framework import serializers

from user.models import CustomUser
from .models import Note, Category, Tag, Comment, Like


class UserSerializer(serializers.ModelSerializer):
    avatar_url = serializers.SerializerMethodField()  # 使用自定义方法返回头像的URL

    class Meta:
        model = CustomUser  # 使用你的用户模型
        fields = ['id', 'username', 'avatar','avatar_url']  # 包括用户ID、名称和头像

    def get_avatar_url(self, obj):
        """替换 avatar 中的 IP 地址"""
        request = self.context.get('request')
        if request and obj.avatar:
            # 构建完整的 URL 并替换 IP
            full_url = request.build_absolute_uri(obj.avatar.url)
            return full_url.replace('0.0.0.0:8053', 'www.zywblog.com')  # 将 'yourdomain.com' 换为你实际的域名或IP
        return None


class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ['id', 'name']  # 仅返回 id 和 name 字段


class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ['id', 'name']  # 只返回标签的 id 和 name


class NoteSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)  # 嵌套用户序列化器
    tags = serializers.ListField(child=serializers.CharField(), write_only=True)  # 接收标签字符串列表（写入时）
    tags_readable = serializers.SerializerMethodField(read_only=True)  # 返回标签列表（读取时）
    like_count = serializers.IntegerField(source='likes.count', read_only=True)  # 点赞数
    comments_count = serializers.IntegerField(source='comments.count', read_only=True)  # 评论数
    category = serializers.PrimaryKeyRelatedField(queryset=Category.objects.all(), write_only=True)  # 通过分类 ID 关联
    category_readable = CategorySerializer(read_only=True, source='category')  # 返回分类详情（读取时）
    content = serializers.CharField(write_only=True)  # 设置 content 为仅写入
    cover_image_url = serializers.SerializerMethodField()

    class Meta:
        model = Note
        fields = ['id', 'user', 'title', 'summary', 'cover_image', 'category', 'category_readable', 'tags',
                  'tags_readable', 'privacy',
                  'created_at', 'updated_at', 'like_count', 'comments_count', 'content','cover_image_url']


    def create(self, validated_data):
        tags_data = validated_data.pop('tags', [])  # 获取标签列表
        category = validated_data.pop('category', None)  # 获取分类
        # 创建 Note 对象
        note = Note.objects.create(**validated_data, category=category)

        # 确保所有标签都存在，并添加到笔记
        tag_objects = []
        for tag_name in tags_data:
            tag_obj, created = Tag.objects.get_or_create(name=tag_name)
            tag_objects.append(tag_obj)

        # 添加标签到笔记
        note.tags.set(tag_objects)  # 使用 set() 替换已有的标签

        return note

    def get_tags_readable(self, obj):
        """返回标签的可读格式"""
        return [tag.name for tag in obj.tags.all()]

    def get_cover_image_url(self, obj):
        request = self.context.get('request')
        if obj.cover_image:
            # 构建完整的 URL
            full_url = request.build_absolute_uri(obj.cover_image.url)
            # 替换掉 IP 地址，例如从 '0.0.0.0' 替换为 'localhost' 或 'yourdomain.com'
            return full_url.replace('0.0.0.0:8053', 'www.zywblog.com')  # 这里将 'yourdomain.com' 换为你实际的域名或IP
        return None


class NoteDataSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)  # 只读字段，返回用户信息
    tags = serializers.ListField(child=serializers.CharField(), write_only=True)  # 接收标签字符串列表
    like_count = serializers.IntegerField(source='likes.count', read_only=True)  # 点赞数
    category = CategorySerializer(read_only=True)  # 使用自定义分类序列化器
    tags_readable = serializers.SerializerMethodField(read_only=True)  # 返回标签列表（读取时）
    liked_by_user = serializers.SerializerMethodField()  # 返回用户是否点赞
    comments_count = serializers.IntegerField(source='comments.count', read_only=True)  # 评论数
    cover_image_url = serializers.SerializerMethodField()

    class Meta:
        model = Note
        fields = ['id', 'user', 'title', 'content', 'summary', 'category', 'tags', 'privacy',
                  'created_at', 'updated_at', 'like_count', 'tags_readable', 'liked_by_user', 'comments_count','cover_image_url']

    def get_tags_readable(self, obj):
        """返回标签的可读格式"""
        return [tag.name for tag in obj.tags.all()]

    def get_liked_by_user(self, obj):
        """判断当前用户是否已点赞该文章"""
        request = self.context.get('request')  # 获取请求上下文中的 request 对象
        if request and request.user.is_authenticated:
            return obj.likes.filter(user=request.user).exists()  # 检查用户是否点赞
        return False  # 用户未登录或未点赞

    def get_cover_image_url(self, obj):
        request = self.context.get('request')
        if obj.cover_image:
            # 构建完整的 URL
            full_url = request.build_absolute_uri(obj.cover_image.url)
            # 替换掉 IP 地址，例如从 '0.0.0.0' 替换为 'localhost' 或 'yourdomain.com'
            return full_url.replace('0.0.0.0:8053', 'www.zywblog.com')  # 这里将 'yourdomain.com' 换为你实际的域名或IP
        return None


class CommentSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    reply = serializers.SerializerMethodField()
    parentId = serializers.SerializerMethodField()
    uid = serializers.SerializerMethodField()
    createTime = serializers.SerializerMethodField()

    class Meta:
        model = Comment
        fields = ['id', 'parentId', 'uid', 'content', 'address', 'likes', 'createTime', 'user', 'reply']

    def get_reply(self, obj):
        replies = obj.replies.all()
        return {
            "total": replies.count(),
            "list": CommentSerializer(replies, many=True).data
        } if replies.exists() else None

    def get_parentId(self, obj):
        return obj.parent.id if obj.parent else None

    def get_uid(self, obj):
        return obj.user.id

    def get_createTime(self, obj):
        return obj.created_at.isoformat()  # ISO 格式化时间


class LikeSerializer(serializers.ModelSerializer):
    user_id = serializers.ReadOnlyField(source='user.id')  # 返回用户ID
    username = serializers.ReadOnlyField(source='user.username')  # 返回用户名

    class Meta:
        model = Like
        fields = ['id', 'user_id', 'username', 'created_at']  # 返回用户ID、名称和创建时间
